package logic

import (
	"common/global"
	"common/model"
	"context"
	"fmt"
	"user_server/proto"
)

func (s *UserServer) GetSignInRecords(ctx context.Context, req *user.GetSignInRecordsRequest) (*user.GetSignInRecordsResponse, error) {
	var records []model.SignRecord
	var total int64

	//初始化数据库查询，筛选出指定用户的签到记录。
	tx := global.Db.Model(&model.SignRecord{}).Where("user_id = ?", req.UserId)
	tx.Count(&total)
	err := tx.Offset(int((req.Page - 1) * req.PageSize)).
		Limit(int(req.PageSize)).
		Find(&records).Error

	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	//将查询到的签到记录转换为响应格式。
	var resRecords []*user.SignInRecord
	for _, r := range records {
		resRecords = append(resRecords, &user.SignInRecord{
			Date:          r.SignDate.Format("2006-01-02"),
			IsRetroactive: int32(r.Type),
		})
	}

	return &user.GetSignInRecordsResponse{
		Records: resRecords,
		Total:   int32(total),
	}, nil
}
